package com.fenrirtec.aepp.common.api;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.GroupDto;
import com.fenrirtec.aepp.common.service.UserManageService;
import com.fenrirtec.aepp.common.service.impl.UserManageServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.JsonUtils;

public class GroupInsertAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(GroupInsertAPI.class);

	public GroupInsertAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
	    UserManageService service = new UserManageServiceImpl();
	    JSONObject jsonObj = JSONObject.parseObject(this.param);
	    String groupName = jsonObj.getString("group_name");
	    List<ErrorInfo> errorList = null;
	    if (StringUtils.isEmpty(groupName)) {
	        errorList = new ArrayList<ErrorInfo>();
	        ErrorInfo error = new ErrorInfo("用户组名错误，请重新输入！", ErrorType.ERROR);
	        errorList.add(error);
	    } else if (service.findByGroupName(groupName) != null) {
	        errorList = new ArrayList<ErrorInfo>();
            ErrorInfo error = new ErrorInfo("用户组已存在，请重新输入！", ErrorType.ERROR);
            errorList.add(error);
	    }
		return errorList;
	}

	@Override
	protected JSONObject doExecute() {
		
		UserManageService service = new UserManageServiceImpl();
		Boolean result = false;
		
		try {
		    JSONObject jsonObj = JSONObject.parseObject(this.param);
		    GroupDto groupDto = JsonUtils.toBean(jsonObj, GroupDto.class);
		    groupDto.setCreateUser(getUserInfo().getLoginName());
		    result = service.insert(groupDto);
			
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}
		
		JSONObject root = new JSONObject();
		root.put("result", result);
		return root;
	}
}
